package com.blog.aspect;

import com.blog.service.NodeService;
import com.blog.utils.FindRequestCacheUtil;
import com.blog.utils.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/*
 * 获取文章前的AOP操作，用来记录访问次数
 * 通过ip绑定访问的文章id来避免计数
 * */
@Aspect
@Component
public class ArticleCommentAspect {

    @Resource(name = "nodeService")
    private NodeService nodeService;

    @Autowired
    private FindRequestCacheUtil cacheUtil;

    /**
     * 这里我们使用注解的形式
     * 当然，我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
     * 切点表达式:   execution(...)
     */
    //评论文章切入点
    @Pointcut("execution(* com.blog.controller.NodeController.insertArticleComment(..))")
    public void insertArticleCommentPointCut() {}

    //评论文章切入点
    @Pointcut("execution(* com.blog.controller.DiaryController.addComment(..))")
    public void addCommentPointCut() {}

    //@AfterReturning：添加文章方法执行前，过滤关键字
    @Around(value = "insertArticleCommentPointCut()")
    public Object insertArticleCommentBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        return replaceWord(joinPoint);
    }

    //@AfterReturning：方添加说说文章法执行前，过滤关键字
    @Around(value = "addCommentPointCut()")
    public Object addCommentBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        return replaceWord(joinPoint);
    }

    //替换敏感文字方法
    public Object replaceWord(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];  //获取第二个参数request域
        String context = (String) args[2];  //获取评论内容
        ServletContext servletContext = request.getSession().getServletContext();
        ArrayList<String> sensitiveWords = (ArrayList<String>) servletContext.getAttribute("sensitiveWords");
        for (String word : sensitiveWords){
            StringBuilder stringBuilder= new StringBuilder();
            for(int i = 0 ; i < word.length() ; i++){
                stringBuilder.append("*");
            }
            context = context.replaceAll(word,stringBuilder.toString());
        }
        args[2] = context;
        return joinPoint.proceed(args);
    }
}
